download_manager.admin = liwe.module ( "download_manager.admin", null, "Download Manager" );

download_manager.admin.dest_div = 'DM-upload-form';

download_manager.admin.init = function ()
{
	if ( ! download_manager.templates )
	{
		console.debug ( "no templates" );
		download_manager.load_templates ( download_manager.admin.init );
		return;
	}
		
		//setTimeout ( download_manager.admin.init, 200 );
        // ===================================================================
        // PUBLIC ATTRIBUTES
        // ===================================================================

	// path to media folder
	this.file_base_path = '/site/download_manager/';
	// destination div for DM
	this.target_div = 'block_main';

        // ===================================================================
        // PRIVATE ATTRIBUTES
        // ===================================================================
	// init vars
	//download_manager.admin.init_mod ();
	// download_manager.admin.load_templates ( download_manager.admin.init_mod );
	download_manager.reset_templates ( 'icons' );
        var _acts = [
                        { func: function () 
				{ 
					download_manager.dest_div = 'system-content' ; 
					download_manager.render (); 
					download_manager.admin.upload_form ( 'DM-upload-form' );
				}, 
				img_src: '', 
				label: 'Gestione Files', "class" : "dm" }
			/*
			{ func: function () 
				{
					download_manager.dest_div = 'system-content' ;
					if ( ! $( 'DM-upload-form' ) )
						download_manager.render ();
					download_manager.admin.upload_form ( 'DM-upload-form' );
				},
				img_src: '',
				label: 'Upload files', "class" : "dm" }
			*/
                ];

        var _plugin = [
                {
                        label:   "DL box",
                        handler: download_manager.admin._jconed_register_handler,
                        context: download_manager.admin._jconed_context
                }
        ];

        download_manager.admin.register ( _acts, _plugin );

};

download_manager.admin.init_mod = function ()
{
	// this function creates download_manager lay-out
	download_manager.admin.upload_form ( 'DM-upload-form' );


};

/* controlla campi form
	- il valore 'action' per ajax deve essere in un campo hidden del form
	- al termine dell'invio chiude il div contenente il form e aggiorna la ricerca
	FIXME:
		 - il form di upload non passa  l'oggetto uploader non viene passato
*/

download_manager.admin._chk_form = function ( form_id )
{
	if ( ! liwe.form.check ( form_id ) ) 
	{
		console.debug ( "%s : check fallito", form_id );
		return;
	}

	var f = liwe.form.get ( form_id );
	var vals = f.get_values();
	console.debug ( vals );
	download_manager.ajax ( vals , function ( data ) 
					{
						//download_manager.admin.close ();
						download_manager.admin.upload_form ();
						download_manager.browse_files ( '' );
					} );
};

download_manager.admin._refresh = function ()
{
	download_manager.admin.close ();
	download_manager.browse_files ( '' );
	
};	

download_manager.admin.upload_form = function ( dest_div, id_obj )
{
	var f = new liwe.form.instance ( download_manager.upload_form_id );

	f.events [ 'complete' ] = 'download_manager.admin._complete';

	if ( ! dest_div ) dest_div = download_manager.admin.dest_div;
	if ( ! id_obj ) id_obj = '';
	
	f.hidden ( "action", "download_manager.admin.add_file" );
	f.hidden ( "id_obj", id_obj );
	f.select ( { name: "module", options: download_manager._mods_list, force_select: false, style: "width:150px;",
			value: download_manager._module } ); //onchange: "download_manager.set_module ( this.value );" } );
	//f.hidden ( "module", download_manager._module );
	f.hidden ( "__PYHP_SESSION", liwe.cookie.get ( "session" ) );

	f.label ( { value: "Rinomina file" } );
	f.text ( { name: "name", maxlength: 200, filter: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_ "} );
	f.label ( { value: "Descrizione" } );
	f.textarea ( { name: "descr", cols: 20, rows: 4 } );
	f.label ( { value: "Upload" } );
	f.uploader ( { name: "upload" } );
	f.label ( { value: "Tags" } );
	f.tags ( { name: "files_tags", module_name: 'download_manager', size: '20' } ); //download_manager._module
	f.submit ( { value: "Invia", nonl: true, "class": "green" } ); 
	//f.button ( { value: "Invia", nonl: true, onclick: "download_manager.admin._chk_form ( 'upload_form' ) " } );
	//f.button ( { value: "close", onclick: "download_manager.admin.close ()" } );
	f.set ( dest_div );
};

download_manager.admin._complete = function ()
{
	download_manager.browse_files ();
};

/*  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	FIXME:  Bachi rilevati:
		- dopo aver inserito delle nuove tags, se si preme il tasto invio, la funzione onblur del campo tag 
		  non viene chiamata e quindi i le tags non vengono inviate
		- Aggiornando un record con delle tags esistenti, queste non vengono separata dalla virgola, ma risultano come un'unica tag
		  ( es: "uno, due, tre" invece di "uno","due","tre" ). Vedere funzione tags.get_value riga 36 di tags.widget.js
*/

download_manager.admin.edit_form = function ( dest_div )
{
	var f = new liwe.form.instance ( 'edit_form' );

	if ( ! dest_div ) dest_div = download_manager.admin.dest_div;
	
	f.hidden ( "action", "download_manager.admin.add_file" );
	f.hidden ( "update", "update"  );
	f.hidden ( "id_file", ""  );
	f.hidden ( "id_obj", ""  );
	//f.select ( { name: "module", options: download_manager._mods_list, force_select: false, style: "width:150px;",
	//		value: download_manager._module } ); //onchange: "download_manager.set_module ( this.value );" } );
	f.hidden ( "module", download_manager._module );
	f.label ( { value: 'Rinomina file' } );
	f.text ( { name: "name", maxlength: 200, filter: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_ "} );
	f.label ( { value: 'Descrizione' } );
	f.textarea ( { name: "descr", cols: 20, rows: 4 } );
	f.label ( { value: 'Tags' } );
	f.tags ( { name: "files_tags", module_name: 'download_manager', size: '20' } ); //download_manager._module
	//f.submit ( { value: "Invia", nonl: true, class: "DM-submit" } ); 
	f.button ( { value: "Salva modifiche", "class": "green", onclick: "download_manager.admin._chk_form ( 'edit_form') " } );
	f.button ( { value: "Carica nuovo file", "class": "blue", onclick: "download_manager.admin._upload_form()" } );

	f.set ( dest_div );
	//download_manager._show_div ( dest_div );
};

// keep id_obj value if it has been set
download_manager.admin._upload_form = function ()
{
	var f = liwe.form.get ( 'edit_form' );
	var vals = f.get_values ();
	download_manager.admin.upload_form ( '', vals.get ( 'id_obj' ) );
};

download_manager.admin.close = function ()
{
	$( 'DM-upload-form' , '' );
};

download_manager.admin._set_form_values = function ( data, cback )
{
	var f = liwe.form.get ( 'edit_form' );
	data [ 'res' ].iterate ( function ( v, k )
					{
						console.debug ( "key: %s - value: %s" , k , v );
						if ( v != '' )
							f.set_value ( k, v );
					}
				);
	if ( cback ) cback ();
};

download_manager.admin.edit_file = function ( id, update, id_obj, cback )
{
	download_manager.admin.edit_form ( '' );
	download_manager.ajax ( { "action": "download_manager.admin.edit_file", "id_file" : id, "update" : update, "id_obj" : id_obj }, function ( data ) 
							{
								download_manager.admin._set_form_values ( data, cback );
								download_manager.tabs.send_event ( 'DM-upload-form', 'click' );
							}  );
};


download_manager.admin.remove_file = function ( path_name, id, id_obj, module )
{
	if ( ! module )
		module = download_manager._module;

	if ( path_name && id ) 
	{
		var uconfirm = confirm ( "Vuoi eliminare il file selzionato ?" );
		if ( uconfirm )
		{
			var vals = {
				"action" : "download_manager.admin.remove_file", 
				"path_name" : path_name, 
				"id_file" : id, 
				"id_obj" : id_obj,
				"module" : module
				};
			download_manager.ajax ( vals, function ( data )
							{
								// 0: no id, 1: errore del db, 2: errore file system
								switch ( data [ 'res' ] )
								{
									case 0:
										alert ( " Impossibile terminare operazione. ID file selezionato mancante " );
										break;
									case 1:
										alert ( " Impossibile terminare operazione. Errore del database " );
										break;
									case 2:
										alert ( " Impossibile terminare operazione. Errore durante la cancellazione del file " );
										break;
									default:
										download_manager.browse_files ();
								}
							} );
		}
	}
};
/* JCONED PLUGIN FUNCTIONS */
download_manager.admin._jconed_register_handler = function ( data ) 
{
	download_manager.admin._jconed_form ();
};

download_manager.admin._jconed_form = function ( data ) 
{

	if ( !  download_manager._ext_list )
	{
		download_manager._get_ext_list ( function ()
			{
				download_manager.admin._jconed_form ( data );
			} );	
	}
	if ( !  download_manager._mods_list )
	{
		download_manager._get_mods_list ( function ()
			{
				download_manager.admin._jconed_form ( data );
			} );	
	}

        var f = new liwe.form.instance ( 'jconed-dl-box-form', 'no-action' ); 
 
        // create filter form 
	f.label ( { value: 'Modulo' } );
        //f.text ( { name: "module", value: download_manager._module } ); 
	f.select ( { name: "module", options: download_manager._mods_list, force_select: false, style: "width:150px;",
		value: download_manager._module, onchange: "download_manager.set_module ( this.value );" } );
	//f.select ( { name: "module", options: download_manager._mods_list, force_select: false, style: "width:150px;",
	//		onchange: function () { download_manager.set_module ( '', 'jconed-dj-box-form' ); } } );
	f.label ( { value: 'ID elemento' } );
        f.text ( { name : "id_obj" } ); 
        f.label ( { value: "Nome file" } ); 
        f.text   ( { name: "name", maxlength: 200 } ); 
        f.label ( { value: "Descrizione" } ); 
        f.text   ( { name: "descr", maxlength: 200 } ); 
        f.label ( { value: "Estensione" } ); 
        f.select ( { name: "fext", options: download_manager._ext_list, force_select: false, style: "width:150px;" } );
        f.label ( { value: "Tags" } );
        f.tags   ( { name: "filters_tags", module: 'download_manager', size: '20' } ); //download_manager._module

        f.hidden ( '_module', 'download_manager' );
        f.hidden ( '_title', 'Download Manager' );

        f.button ( { value: "Conferma", onclick: "jconed.render_plugin('jconed-dl-box-form')" } );

        f.button ( { value: "Preview", 'class': 'green', onclick: download_manager.admin._jconed_dl_box_preview } );
        //f.button ( { value: "Reset", 'class': 'yellow', onclick: this.form.reset() } );
        
        f.workspace ( { name: 'jconed-dl-box-preview' } );
	
	//f.set ( jcontxt );
	jconed.toolbar.set_context ( f.get () );

	if ( data )
	{
		f._fields.iterate ( function ( field )
			{
				if ( data.get ( field ) )
					f.set_value ( field, data.field );
			} );
	} 
};

download_manager.admin._jconed_context = function ()
{
        var item = jconed.get_plugin_selection ();
        if ( ! item ) return;
        if ( ! liwe.dom.has_class ( item, 'liwe-plugin-download_manager' ) ) return;

        pre = item.getElementsByTagName ( "pre" );
        if ( ! pre.length ) return;

        pre = pre [ 0 ];

        var values = null;
        eval ( 'values = ' + pre.innerHTML );

        download_manager.admin._jconed_form ( values [ 'params' ] );
};

download_manager.admin._jconed_dl_box_preview = function ()
{
        var f = liwe.form.get ( 'jconed-dl-box-form' );
        var params = f.get_values ();
        var module = params.get ( 'module', 'download_manager' );
        
        download_manager.dl_box ( params, 'jconed-dl-box-preview', module, 'list' );
};      
